package com.jindi.appuser.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.github.wxpay.sdk.WXPay;
import com.jindi.appuser.common.*;
import com.jindi.appuser.controller.util.ALiConstants;
import com.jindi.appuser.controller.util.PayUtil;
import com.jindi.appuser.dao.AppMapper;
import com.jindi.appuser.dao.OrderMapper;
import com.jindi.appuser.dao.UserMapper;
import com.jindi.appuser.dao.YysPriceMapper;
import com.jindi.appuser.domain.App;
import com.jindi.appuser.domain.Order;
import com.jindi.appuser.domain.User;
import com.jindi.appuser.domain.YysPrice;
import com.jindi.appuser.service.PayService;
import com.jindi.appuser.util.LotUtil;
import com.jindi.appuser.util.XMLUtil;
import com.jindi.appuser.util.weixin.MyConfig;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.logging.Logger;

@Service
public class PayServiceImpl implements PayService {
    private static Logger logger = Logger.getLogger(PayServiceImpl.class.getName());
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private YysPriceMapper yysPriceMapper;
    @Autowired
    private AppMapper appMapper;

    public static final String APP_URL = "https://yys.jindi163.com/";
    public static final String CHECK_ALI_URL = "app/pay_yys/checkAliSign.do";
    public static final String CHECK_ALI_URL_PRICE = "app/pay_price/checkAliSignPrice.do";
    public static final String CHECK_WECHAT_URL_PRICE = "app/pay_price/checkWechatSign.do";
    public static final String CHECK_WECHAT_URL = "app/pay_yys/checkWechatSign.do";
    public static final String QUICK_MSECURITY_PAY = "QUICK_MSECURITY_PAY";

    @Override
    public ServerResponse payByAli(String uid, String os,  String total_amount, String timeout_express) {

        Map<String, String> params = new HashMap<String, String>();
        params.put("os", os);
       // params.put("priceKey", priceKey);
        Date date = new Date();
        Random rd = new Random();
        String notify_url = APP_URL + CHECK_ALI_URL;

        // 商户网站唯一订单号
        String out_trade_no = DateConverter.dateToString(date) + (rd.nextInt(90000) + 10000) + "";
        String producr_code = QUICK_MSECURITY_PAY;

        App priceCycle = appMapper.selectByOs(os);
        // 商品简单描述
        String body = "永久";
        //String body = checkSetMeal(total_amount,priceCycle,priceKey);

        if (total_amount == null || !total_amount.equals(priceCycle.getPrice())){
            logger.info("支付金额："+total_amount);
            return  ServerResponse.createByErrorMessage("支付金额异常");
        }
        AlipayClient alipayClient = new DefaultAlipayClient(ALiConstants.ALIMETHOD,
                ALiConstants.APPID, ALiConstants.PRIVATEKEY, "json", ALiConstants.CHARSET,
                ALiConstants.ALIPUBLICKEY, ALiConstants.SIGNTYPE);

        // 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        // SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(body.replace(" ", ""));
        model.setSubject(priceCycle.getName().replace(" ", ""));
        model.setOutTradeNo(out_trade_no);
        model.setTimeoutExpress(timeout_express == null ? "30m" : timeout_express);
        model.setTotalAmount(total_amount );
        model.setProductCode(producr_code);
        request.setBizModel(model);
        request.setNotifyUrl(notify_url);
        try {
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            //todo 订单
            Order order = new Order(null, uid,out_trade_no, total_amount, 1, 0, "", "", body, priceCycle.getName(), "", "", null,
                    new Date(), new Date());
            int index =orderMapper.insertSelective(order);

           if (index>0){
                logger.info("=====支付宝订单创建成功=====订单金额："+total_amount);
            }
            params.put("out_trade_no", out_trade_no);
            params.put("datas", response.getBody());

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        logger.info("=====payByAli=====appId:"+params.get("appId"));
        logger.info("=====payByAli=====priceKey:"+params.get("priceKey"));
        return ServerResponse.createBySuccess(params);
    }

 /*   private String checkSetMeal(String total_amount, App priceCycle) {
        if(total_amount.equals(EmptyUtil.toString(priceCycle.getPrice()))){
            return "永久";
        }
        return null;
    }*/

    @Override
    public String checkAliSign(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map<?, ?> requestParams = request.getParameterMap();
        for (Iterator<?> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。
            /*try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }*/
            // System.out.println("aliName---->"+name+",valueStr-->"+valueStr);
            params.put(name, valueStr);
            logger.info("=====valueStr=====valueStr:"+valueStr);
            logger.info(name+":"+params.get(name));
        }
        // 切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        // boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String
        // publicKey, String charset, String sign_type)
        try {
            //异步验签
            boolean flag = AlipaySignature.rsaCheckV1(params, ALiConstants.ALIPUBLICKEY, ALiConstants.CHARSET, "RSA2");
            Order orderRecord =orderMapper.queryByOutTradeNo(params.get("out_trade_no"));
            if (flag) {
                if (orderRecord != null) {
                    orderRecord.setAliSign(params.get("sign"));
                    orderRecord.setUserAliId(params.get("buyer_id"));
                    orderRecord.setUserAlipay(params.get("buyer_logon_id"));
                    orderRecord.setGmtPayment(DateConverter.stringToDate(params.get("gmt_payment"), "yyyy-MM-dd HH:mm:ss"));
                    orderRecord.setReceiptAmount(PayUtil.getRealPrice(1,params.get("receipt_amount").toString()));
                    orderRecord.setAliOrderId(params.get("trade_no"));
                    //判断是否验签成功
                    if ("TRADE_SUCCESS".equals(params.get("trade_status"))) {
                        logger.info("=====支付宝验签成功======"+params.get("trade_status"));
                        orderRecord.setPayStatus(1);
                        //Double integral = orderRecord.getReceiptAmount()*10;//积分类型装换
                        User user = userMapper.selectByPrimaryKey(Integer.parseInt(orderRecord.getUid()));
                        if (!EmptyUtil.isEmpty(user)){
                            App priceCycle = appMapper.selectByPrimaryKey(Integer.parseInt(params.get("appId")==null?"15":params.get("appId")));
                            //user.setIntegral((user.getIntegral()== null ? 0 :user.getIntegral())+integral.intValue());
                            //user.setTotalConsumption((user.getTotalConsumption()== null ? 0 :user.getTotalConsumption())+Double.parseDouble(orderRecord.getTotalAmount()));
                            Calendar cal = Calendar.getInstance();// 取当前日期。
                            //判断会员是否过期
                            if (TimeUtils.compareDate(user.getEndTime()==null?new Date():user.getEndTime(), new Date()) == 1) {
                                cal.setTime(user.getEndTime());
                            }
                            logger.info("=====购买前的有效日期======"+user.getEndTime());
                            //cal=changeTime(cal,Double.parseDouble(orderRecord.getTotalAmount()),priceCycle);
                           // user.setEndTime(cal.getTime());
                            user.setRole("2");
                            userMapper.updateByPrimaryKeySelective(user);
                        }
                        orderMapper.updateByPrimaryKeySelective(orderRecord);
                        return "success";
                    } else {
                        orderRecord.setPayStatus(2);
                        //添加消费记录
                        orderMapper.updateByPrimaryKeySelective(orderRecord);
                        return "fail";
                    }
                }
            }
        }catch (AlipayApiException e){
            e.printStackTrace();
            logger.info("=====支付宝验签报错======"+e);
        }
        logger.info("=====支付宝验签报错======"+params.get("trade_status"));
        return "fail";
    }




    @Override
    public ServerResponse payByWechat(String uid, String os,  String total_amount, HttpServletRequest request) {
        Date date = new Date();
        Random rd = new Random();
        Map<String, String> params = new HashMap<String, String>();

        App priceCycle = appMapper.selectByOs(os);
        // 商品简单描述
        String body = "永久";
        if (total_amount == null|| !total_amount.equals(priceCycle.getPrice())){
            logger.info("支付金额："+total_amount);
            return  ServerResponse.createByErrorMessage("支付金额异常");
        }
        String cash = total_amount;
        String subject = priceCycle.getName();
        // 用户端ip
        String spbill_create_ip = HttpRequest.getIPAddr(request);
        // 异步通知服务器url
        String notify_url = APP_URL+CHECK_WECHAT_URL;
        // 随机字符串
        String nonce_str = LotUtil.createRandomString(32).toUpperCase();
        // 商品订单号
        String out_trade_no = DateConverter.dateToString(date) + (rd.nextInt(90000) + 10000) + "";

        MyConfig config = null;
        try {
            config = new MyConfig();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", subject+body+"套餐");
        data.put("out_trade_no", out_trade_no);
        data.put("fee_type", "CNY");
        if(LotUtil.isNumeric(total_amount)) {//微信金额单位为分
            int a = (int) (100 * Double.valueOf(total_amount));
            total_amount = "" + a;
        }
        data.put("total_fee", total_amount);
        data.put("spbill_create_ip", spbill_create_ip);
        data.put("notify_url", notify_url);
        data.put("trade_type", "APP");
        Map<String, String> resps = null;
        logger.info(data.toString());
        try {
            resps = wxpay.unifiedOrder(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info(resps.toString());
        String prepay_id = resps.get("prepay_id");
        String timestamp = (date.getTime() / 1000) + "";
        String packages = "Sign=WXPay";
        String sign = resps.get("sign");
        sign = "appid=" + config.getAppID() + "&noncestr=" + nonce_str + "&package=" + packages
                + "&partnerid=" + config.getMchID() + "&prepayid=" + prepay_id + "&timestamp=" + timestamp
                + "&key=" + config.getKey();
        logger.info("========微信支付sign："+sign+"========");
        sign = DigestUtils.md5Hex(sign).toUpperCase();
        Order order = new Order(null ,uid, out_trade_no, cash, 2, 0, "", sign, body,
                subject, "", "", null, new Date(), new Date());
        logger.info("=====微信订单创建=====订单号："+order.getOutTradeNo());
        int index=orderMapper.insertSelective(order);
        if (index>0){
            logger.info("=====微信订单创建成功=====订单金额："+cash);
        }
        params.put("out_trade_no", out_trade_no);
        params.put("nonce_str", nonce_str);
        params.put("sign", sign);
        params.put("prepay_id", prepay_id);
        params.put("timestamp", timestamp);
        params.put("os", os);
        return ServerResponse.createBySuccess(params);
    }

    @Override
    public String checkWechatSign(HttpServletRequest request) {
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] bt = new byte[1024];
        int len = 0;
        Map<String, String> map = new HashMap<String, String>();
        try {
            inputStream = request.getInputStream();
            while((len = inputStream.read(bt)) != -1){
                outputStream.write(bt,0,len);
            }
            outputStream.close();
            inputStream.close();
            String result = new String(outputStream.toByteArray(),"UTF-8");
            map = XMLUtil.doXMLParse(result);
            Order order = orderMapper.queryByOutTradeNo(map.get("out_trade_no"));
            if (order != null) {
                order.setAliSign(map.get("sign"));
                order.setGmtPayment(DateConverter.stringToDate(map.get("time_end"), "yyyyMMddHHmmss"));
                Double price = Double.parseDouble(!EmptyUtil.isEmpty(map.get("cash_fee")) ?
                        (LotUtil.isNumeric(map.get("cash_fee")) ? map.get("cash_fee") : "0" ): "0")/100;
                order.setReceiptAmount(PayUtil.getRealPrice(2,price.toString()));
                order.setAliOrderId(map.get("trade_no"));
                if ("SUCCESS".equalsIgnoreCase(map.get("return_code").toString())) {
                    if("SUCCESS".equalsIgnoreCase(map.get("result_code").toString())){
                        logger.info("=====微信支付验签成功====="+map.get("result_code").toString()+map.get("return_code").toString());
                        order.setPayStatus(1);
                        User user = userMapper.selectByPrimaryKey(Integer.parseInt(order.getUid()));
                        if (!EmptyUtil.isEmpty(user)){
                            Calendar cal = Calendar.getInstance();// 取当前日期。
                            if (TimeUtils.compareDate(user.getEndTime()==null?new Date():user.getEndTime(), new Date()) == 1) {
                                cal.setTime(user.getEndTime());
                            }
                            user.setRole("2");
                            userMapper.updateByPrimaryKeySelective(user);
                        }
                        //添加积分明细
                       /* IntegralDetail integralDetail = new IntegralDetail(null,order.getUid(),integral.intValue(),
                                "购买"+order.getSubject()+order.getBody()+"套餐奖励", 4, new Date());
                        integralMapper.insertSelective(integralDetail);*/
                        orderMapper.updateByPrimaryKeySelective(order);
                        logger.info("=====微信支付验签成功=====");
                        return XMLUtil.setXML("SUCCESS", "OK");
                    }
                }else {
                    order.setPayStatus(2);
                    orderMapper.updateByPrimaryKeySelective(order);
                    logger.info("=====微信支付验签失败=====");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int removeOrder() {
        return orderMapper.deleteByPayStatus();
    }

    @Override
    public ServerResponse payByAliPrice(String uid, String os, String total_amount, String timeout_express, String priceId) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("os", os);
        // params.put("priceKey", priceKey);
        Date date = new Date();
        Random rd = new Random();
        String notify_url = APP_URL + CHECK_ALI_URL_PRICE;

        // 商户网站唯一订单号
        String out_trade_no = DateConverter.dateToString(date) + (rd.nextInt(90000) + 10000) + "";
        String producr_code = QUICK_MSECURITY_PAY;

        // 商品简单描述
        String body = "次数";
        //String body = checkSetMeal(total_amount,priceCycle,priceKey);
        YysPrice yysPrice = yysPriceMapper.selectByPrimaryKey(Integer.parseInt(priceId));

        if (total_amount == null || !total_amount.equals(yysPrice.getPrice())){
            logger.info("支付金额："+total_amount);
            return  ServerResponse.createByErrorMessage("支付金额异常");
        }
        AlipayClient alipayClient = new DefaultAlipayClient(ALiConstants.ALIMETHOD,
                ALiConstants.APPID, ALiConstants.PRIVATEKEY, "json", ALiConstants.CHARSET,
                ALiConstants.ALIPUBLICKEY, ALiConstants.SIGNTYPE);

        // 实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        // SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(body.replace(" ", ""));
        model.setSubject("抽奖".replace(" ", ""));
        model.setOutTradeNo(out_trade_no);
        model.setTimeoutExpress(timeout_express == null ? "30m" : timeout_express);
        model.setTotalAmount(total_amount );
        model.setProductCode(producr_code);
        request.setBizModel(model);
        request.setNotifyUrl(notify_url);
        try {
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            //todo 订单
            Order order = new Order(null, uid,out_trade_no, total_amount, 1, 0, "", "", body, "铃声", "", "", null,
                    new Date(), new Date());
            int index =orderMapper.insertSelective(order);

            if (index>0){
                logger.info("=====支付宝订单创建成功=====订单金额："+total_amount);
            }
            params.put("out_trade_no", out_trade_no);
            params.put("datas", response.getBody());

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ServerResponse.createBySuccess(params);
    }

    @Override
    public String checkAliSignPrice(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map<?, ?> requestParams = request.getParameterMap();
        for (Iterator<?> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
            logger.info("=====valueStr=====valueStr:"+valueStr);
            logger.info(name+":"+params.get(name));
        }
        try {
            //异步验签
            boolean flag = AlipaySignature.rsaCheckV1(params, ALiConstants.ALIPUBLICKEY, ALiConstants.CHARSET, "RSA2");
            Order orderRecord =orderMapper.queryByOutTradeNo(params.get("out_trade_no"));
            if (flag) {
                if (orderRecord != null) {
                    orderRecord.setAliSign(params.get("sign"));
                    orderRecord.setUserAliId(params.get("buyer_id"));
                    orderRecord.setUserAlipay(params.get("buyer_logon_id"));
                    orderRecord.setGmtPayment(DateConverter.stringToDate(params.get("gmt_payment"), "yyyy-MM-dd HH:mm:ss"));
                    orderRecord.setReceiptAmount(PayUtil.getRealPrice(1,params.get("receipt_amount").toString()));
                    orderRecord.setAliOrderId(params.get("trade_no"));
                    //判断是否验签成功
                    if ("TRADE_SUCCESS".equals(params.get("trade_status"))) {
                        logger.info("=====支付宝验签成功======"+params.get("trade_status"));
                        orderRecord.setPayStatus(1);
                        //Double integral = orderRecord.getReceiptAmount()*10;//积分类型装换
                        User user = userMapper.selectByPrimaryKey(Integer.parseInt(orderRecord.getUid()));
                        if (!EmptyUtil.isEmpty(user)){
                            App priceCycle = appMapper.selectByPrimaryKey(Integer.parseInt(params.get("appId")==null?"15":params.get("appId")));
                            //user.setIntegral((user.getIntegral()== null ? 0 :user.getIntegral())+integral.intValue());
                            //user.setTotalConsumption((user.getTotalConsumption()== null ? 0 :user.getTotalConsumption())+Double.parseDouble(orderRecord.getTotalAmount()));
                            //判断会员是否过期

                            logger.info("======receipt_amount====="+orderRecord.getTotalAmount());

                            YysPrice yysPrice = yysPriceMapper.selectByPrice(orderRecord.getTotalAmount());

                            logger.info("=====购买的的次数======"+yysPrice.getCount());

                            logger.info("=====购买前的次数======"+user.getCountDraw());
                            //cal=changeTime(cal,Double.parseDouble(orderRecord.getTotalAmount()),priceCycle);
                            // user.setEndTime(cal.getTime());
                            if(!"1".equals(user.getFirstPay()) ){
                                user.setFirstPay("2");
                            }
                            user.setCountDraw(EmptyUtil.toString(Integer.parseInt(EmptyUtil.isEmpty(user.getCountDraw())?"0":user.getCountDraw())+yysPrice.getCount()));
                            userMapper.updateByPrimaryKeySelective(user);
                            logger.info("=====购买后的次数======"+user.getCountDraw());
                        }
                        orderMapper.updateByPrimaryKeySelective(orderRecord);
                        return "success";
                    } else {
                        orderRecord.setPayStatus(2);
                        //添加消费记录
                        orderMapper.updateByPrimaryKeySelective(orderRecord);
                        return "fail";
                    }
                }
            }
        }catch (AlipayApiException e){
            e.printStackTrace();
            logger.info("=====支付宝验签报错======"+e);
        }
        logger.info("=====支付宝验签报错======"+params.get("trade_status"));
        return "fail";
    }

    @Override
    public ServerResponse payByWechatPrice(String uid, String os, String total_amount, HttpServletRequest request, String priceId) {
        Date date = new Date();
        Random rd = new Random();
        Map<String, String> params = new HashMap<String, String>();

      //  App priceCycle = appMapper.selectByOs(os);

        YysPrice yysPrice = yysPriceMapper.selectByPrimaryKey(Integer.parseInt(priceId));

        // 商品简单描述
        String body = "抽奖";
        if (total_amount == null|| !total_amount.equals(yysPrice.getPrice())){
            logger.info("支付金额："+total_amount);
            return  ServerResponse.createByErrorMessage("支付金额异常");
        }
        String cash = total_amount;
        String subject = "次数";
        // 用户端ip
        String spbill_create_ip = HttpRequest.getIPAddr(request);
        // 异步通知服务器url
        String notify_url = APP_URL+CHECK_WECHAT_URL_PRICE;
        // 随机字符串
        String nonce_str = LotUtil.createRandomString(32).toUpperCase();
        // 商品订单号
        String out_trade_no = DateConverter.dateToString(date) + (rd.nextInt(90000) + 10000) + "";

        MyConfig config = null;
        try {
            config = new MyConfig();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        WXPay wxpay = new WXPay(config);
        Map<String, String> data = new HashMap<String, String>();
        data.put("body", subject);
        data.put("out_trade_no", out_trade_no);
        data.put("fee_type", "CNY");
        if(LotUtil.isNumeric(total_amount)) {//微信金额单位为分
            int a = (int) (100 * Double.valueOf(total_amount));
            total_amount = "" + a;
        }
        data.put("total_fee", total_amount);
        data.put("spbill_create_ip", spbill_create_ip);
        data.put("notify_url", notify_url);
        data.put("trade_type", "APP");
        Map<String, String> resps = null;
        logger.info(data.toString());
        try {
            resps = wxpay.unifiedOrder(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info(resps.toString());
        String prepay_id = resps.get("prepay_id");
        String timestamp = (date.getTime() / 1000) + "";
        String packages = "Sign=WXPay";
        String sign = resps.get("sign");
        sign = "appid=" + config.getAppID() + "&noncestr=" + nonce_str + "&package=" + packages
                + "&partnerid=" + config.getMchID() + "&prepayid=" + prepay_id + "&timestamp=" + timestamp
                + "&key=" + config.getKey();
        logger.info("========微信支付sign："+sign+"========");
        sign = DigestUtils.md5Hex(sign).toUpperCase();
        Order order = new Order(null ,uid, out_trade_no, cash, 2, 0, "", sign, body,
                subject, "", "", null, new Date(), new Date());
        logger.info("=====微信订单创建=====订单号："+order.getOutTradeNo());
        int index=orderMapper.insertSelective(order);
        if (index>0){
            logger.info("=====微信订单创建成功=====订单金额："+cash);
        }
        params.put("out_trade_no", out_trade_no);
        params.put("nonce_str", nonce_str);
        params.put("sign", sign);
        params.put("prepay_id", prepay_id);
        params.put("timestamp", timestamp);
        params.put("os", os);
        return ServerResponse.createBySuccess(params);
    }

    @Override
    public String checkWechatSignPrice(HttpServletRequest request) {
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] bt = new byte[1024];
        int len = 0;
        Map<String, String> map = new HashMap<String, String>();
        try {
            inputStream = request.getInputStream();
            while((len = inputStream.read(bt)) != -1){
                outputStream.write(bt,0,len);
            }
            outputStream.close();
            inputStream.close();
            String result = new String(outputStream.toByteArray(),"UTF-8");
            map = XMLUtil.doXMLParse(result);
            Order order = orderMapper.queryByOutTradeNo(map.get("out_trade_no"));
            if (order != null) {
                order.setAliSign(map.get("sign"));
                order.setGmtPayment(DateConverter.stringToDate(map.get("time_end"), "yyyyMMddHHmmss"));
                Double price = Double.parseDouble(!EmptyUtil.isEmpty(map.get("cash_fee")) ?
                        (LotUtil.isNumeric(map.get("cash_fee")) ? map.get("cash_fee") : "0" ): "0")/100;
                order.setReceiptAmount(PayUtil.getRealPrice(2,price.toString()));
                order.setAliOrderId(map.get("trade_no"));
                if ("SUCCESS".equalsIgnoreCase(map.get("return_code").toString())) {
                    if("SUCCESS".equalsIgnoreCase(map.get("result_code").toString())){
                        logger.info("=====微信支付验签成功====="+map.get("result_code").toString()+map.get("return_code").toString());
                        order.setPayStatus(1);
                        User user = userMapper.selectByPrimaryKey(Integer.parseInt(order.getUid()));
                        if (!EmptyUtil.isEmpty(user)){

                           /* Calendar cal = Calendar.getInstance();// 取当前日期。
                            if (TimeUtils.compareDate(user.getEndTime()==null?new Date():user.getEndTime(), new Date()) == 1) {
                                cal.setTime(user.getEndTime());
                            }*/
                            logger.info(order.getTotalAmount());
                            YysPrice yysPrice = yysPriceMapper.selectByPrice(order.getTotalAmount());

                            if(!"1".equals(user.getFirstPay()) ){
                                user.setFirstPay("2");
                            }
                            logger.info("=====购买的次数====="+yysPrice.getCount());
                            logger.info("=====购买前的次数====="+user.getCountDraw());
                            user.setCountDraw(EmptyUtil.toString(Integer.parseInt(EmptyUtil.isEmpty(user.getCountDraw())?"0":user.getCountDraw())+yysPrice.getCount()));
                            userMapper.updateByPrimaryKeySelective(user);
                            logger.info("=====购买后的次数====="+user.getCountDraw());
                        }
                        orderMapper.updateByPrimaryKeySelective(order);
                        logger.info("=====微信支付验签成功=====");
                        return XMLUtil.setXML("SUCCESS", "OK");
                    }
                }else {
                    order.setPayStatus(2);
                    orderMapper.updateByPrimaryKeySelective(order);
                    logger.info("=====微信支付验签失败=====");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
